<template>
  <div>
    <TopTitle :texttitle="'城市列表'" :gourl="'/home'"></TopTitle>
    
    <van-index-bar :index-list="MyIndex" class="navindex">
      <div v-for="item in cityList" :key="item.cityindex" class="a">
        <van-index-anchor index="1">{{ item.cityindex }}</van-index-anchor>
        <van-cell
          :title="item.label"
          v-for="item in item.citydata"
          :key="item.value"
          @click="goHome(item)"
        />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import { citylistName,hotcity } from '@/api/Interface.js'
import TopTitle from '@/components/TopTitle.vue'


export default {
  components:{
    TopTitle
  },

  data() {
    return {
      cityList: [],
      MyIndex: [
        '#',
        '热门',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z',
      ],
    }
  },
  methods:{
    goHome(value){
      localStorage.setItem('labelCity',JSON.stringify(value));
      this.$router.back()
    }
  },
  async created() {
    let cityCont = []
    // 发起获取全部城市数据请求
    const cityres = await citylistName()
    cityres.body.map((item) => {
      // 将数据中的首字母进行加工
      item.short = item.short[0].toUpperCase()
    })
    this.MyIndex.forEach(item => {
      cityCont.push({cityindex:item,citydata:[]})
    })
    const {body:hostres} = await hotcity()
    
    hostres.map(item => {
      cityCont[1].citydata.push(item)
    })

    // 将相同首字母的城市放到一起
    cityCont.map(item =>{
      cityres.body.map(el => {
        if(item.cityindex == el.short) {
            item.citydata.push(el)
        }
      })
    })
    // 赋值给准备好的data中的空数组，进行循环渲染
    this.cityList = [...cityCont,...this.cityList]
    console.log(cityCont);
  },
}
</script>

<style scoped>
  .van-index-bar__index{
    margin-top: 15px !important;
  }
</style>
